import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:qaun_ni_dev/utils/toast.dart';

class LoginProvider with ChangeNotifier {
  String userName = '';
  String userPwd = '';

  var themeData = ThemeData(primaryColor: Colors.pink,);


  // 登录
  Future  loginCheck (context,userName,userPwd) async {
    try {
      Dio dio = new Dio();
      String url = 'http://120.76.60.190:8081/mgr/sysUser/login';
      Response response;
      response =  await dio.post(
          url,
          queryParameters: {"pwd": userPwd, "userName": userName }
      );
      dynamic responses = jsonDecode(response.toString());
      Map<String, dynamic>.from(responses);
      print('${response}');
      print({'登录成功返回的数据': responses['data']['token']});
      var code =   responses['code'];
      if(code != 200) {
        Toast.toast(context, msg: '登录失败，请重新输入');
        return false;
      } else {
        final userToken = responses['data']['token'];
        final prefs = await SharedPreferences.getInstance();
        final setTokenResult = await prefs.setString('user_token', userToken);
        if(setTokenResult != null){
          print('保存登录token成功');
          Navigator.of(context).pushNamedAndRemoveUntil('/homePage', (route) => route == null,);
        }else{
          print('error, 保存登录token失败');
        }
        return userToken;
      }

    } catch  (e){
      Toast.toast(context,msg: '登录连接发生错误');
      print({'发生错误': e});
    }
    notifyListeners();
  }
  // 退出
  Future deleteUserToken (context) async {
    final prefs = await SharedPreferences.getInstance();
    final result = await prefs.clear();

    if (result) {
      debugPrint('退出登录成功');
      Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => route == null,);
    }
    notifyListeners();
  }

  // 改变主题

  changeTheme1() {
    themeData =  ThemeData(primaryColor: Colors.pink,);
    notifyListeners();
  }

  changeTheme2() {
    themeData =  ThemeData(primaryColor: Colors.blueAccent,);
    notifyListeners();
  }
}